package cn.iocoder.yudao.module.wine.service.complaininfo;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.wine.controller.app.complaininfo.vo.AppComplainInfoPageReqVO;
import cn.iocoder.yudao.module.wine.controller.app.complaininfo.vo.AppComplainInfoRespVO;
import cn.iocoder.yudao.module.wine.controller.app.complaininfo.vo.AppComplainInfoSaveReqVO;
import cn.iocoder.yudao.module.wine.controller.app.userfans.enums.UserFansSubscribeEnum;
import cn.iocoder.yudao.module.wine.dal.dataobject.businessuser.BusinessUserDO;
import cn.iocoder.yudao.module.wine.dal.mysql.businessuser.BusinessUserMapper;
import cn.iocoder.yudao.module.wine.enums.BusinessUserEnum;
import cn.iocoder.yudao.module.wine.enums.LeaveInfoAuditEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

import cn.iocoder.yudao.module.wine.controller.admin.complaininfo.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.complaininfo.ComplainInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wine.dal.mysql.complaininfo.ComplainInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.*;

/**
 * 投诉信息 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ComplainInfoServiceImpl implements ComplainInfoService {

    @Resource
    private ComplainInfoMapper complainInfoMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private BusinessUserMapper businessUserMapper;


    @Override
    public Long createComplainInfo(ComplainInfoSaveReqVO createReqVO) {
        // 插入
        ComplainInfoDO complainInfo = BeanUtils.toBean(createReqVO, ComplainInfoDO.class);
        complainInfoMapper.insert(complainInfo);
        // 返回
        return complainInfo.getId();
    }

    @Override
    public void updateComplainInfo(ComplainInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateComplainInfoExists(updateReqVO.getId());
        // 更新
        ComplainInfoDO updateObj = BeanUtils.toBean(updateReqVO, ComplainInfoDO.class);
        complainInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteComplainInfo(Long id) {
        // 校验存在
        validateComplainInfoExists(id);
        // 删除
        complainInfoMapper.deleteById(id);
    }

    private ComplainInfoDO validateComplainInfoExists(Long id) {
        ComplainInfoDO complainInfoDO = complainInfoMapper.selectById(id);
        if (complainInfoDO == null) {
            throw exception(INFO_NOT_EXISTS);
        } else {
            return complainInfoDO;
        }
    }

    @Override
    public ComplainInfoDO getComplainInfo(Long id) {
        ComplainInfoDO complainInfo =  complainInfoMapper.selectById(id);
        return complainInfo;
    }

    @Override
    public PageResult<ComplainInfoRespVO> getComplainInfoPage(ComplainInfoPageReqVO pageReqVO) {
        return complainInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<AppComplainInfoRespVO> getComplainInfoList(AppComplainInfoPageReqVO pageReqVO) {
        return complainInfoMapper.selectComplainInfoList(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appDeleteComplainInfo(Long id) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        //检查商家认证状态
        authBusinessUser();

        ComplainInfoDO complainInfoDO = validateComplainInfoExists(id);
        if (complainInfoDO.getUserId().equals(loginUserId)) {
            complainInfoMapper.deleteById(id);
        } else {
            throw exception(HAVE_NO_RIGHT_COMPLAIN);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appUpdateComplainInfo(AppComplainInfoSaveReqVO updateReqVO) {
        ComplainInfoDO complainInfoDO = BeanUtils.toBean(updateReqVO, ComplainInfoDO.class);
        ComplainInfoDO data = validateComplainInfoExists(complainInfoDO.getId());
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        MemberUserRespDTO user = memberUserApi.getUser(loginUserId);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        //检查商家认证状态
        authBusinessUser();

        if (!data.getUserId().equals(loginUserId)) {
            throw exception(HAVE_NO_RIGHT_COMPLAIN);
        }
        //判断该用户发布的内容是否需要审核
        //if (AuditEnum.NO_AUDIT_REQUIRED.getCode().equals(user.getAudit())) {
        //    complainInfoDO.setAudit(LeaveInfoAuditEnum.PASS_THE_AUDIT.getCode());
        //} else {
        //    complainInfoDO.setAudit(LeaveInfoAuditEnum.AUDIT.getCode());
        //}
        //修改成发布投诉都需要审核09.01
        complainInfoDO.setAudit(LeaveInfoAuditEnum.AUDIT.getCode());

        complainInfoMapper.updateById(complainInfoDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer appCreateComplainInfo(AppComplainInfoSaveReqVO createReqVO) {
        ComplainInfoDO bean = BeanUtils.toBean(createReqVO, ComplainInfoDO.class);

        //当infoId>0时判断是否重复发布
        Long infoId = bean.getInfoId();
        if (infoId >0) {
            ComplainInfoDO complainInfoDO = complainInfoMapper.selectByInfoId(infoId);
            if (complainInfoDO != null) {
                throw exception(REPEAT_ADDITION);
            }
        }

        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        //查询会员信息
        MemberUserRespDTO user = memberUserApi.getUser(loginUserId);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        //检查商家认证状态
        BusinessUserDO businessUserDO = authBusinessUser();

        bean.setUserId(loginUserId);

        LocalDateTime createTime = user.getCreateTime();
        //获取下个月今天
        LocalDateTime plusMonthDateTime = createTime.plusMonths(1);
        int i = plusMonthDateTime.compareTo(LocalDateTime.now());
        if (i < 0){
            //判断用户是否剩余发布条数
            Integer complainNum = businessUserDO.getComplainNum();
            //可发布数为0 抛出异常
            if (complainNum.equals(0)) {
                throw exception(COUNT_ZERO);
            }
            if (complainNum > 0) {
                //可发布数减1
                businessUserDO.setComplainNum(businessUserDO.getComplainNum() - 1);
                businessUserMapper.updateById(businessUserDO);
            }
        }

        //判断该用户发布的内容是否需要审核
        //if (AuditEnum.NO_AUDIT_REQUIRED.getCode().equals(user.getAudit())) {
        //    bean.setAudit(LeaveInfoAuditEnum.PASS_THE_AUDIT.getCode());
        //} else {
        //    bean.setAudit(LeaveInfoAuditEnum.AUDIT.getCode());
        //}
        //修改成发布投诉都需要审核09.01
        bean.setAudit(LeaveInfoAuditEnum.AUDIT.getCode());

        return complainInfoMapper.insert(bean);
    }

    @Override
    public AppComplainInfoRespVO appGetComplainInfo(Long id) {
        AppComplainInfoRespVO data = complainInfoMapper.getJoinInfoById(id);
        validateComplainInfoExists(id);
        // 关注状态为空，设置未关注状态
        if (data.getSubscribeStatus() == null) {
            data.setSubscribeStatus(UserFansSubscribeEnum.UNFOLLOW.getStatus());
        }
        ComplainInfoDO bean = BeanUtils.toBean(data, ComplainInfoDO.class);
        bean.setViewCount(bean.getViewCount() + 1);
        complainInfoMapper.updateById(bean);
        return data;
    }

    @Override
    public List<AppComplainInfoRespVO> getMyPublishList(AppComplainInfoPageReqVO pageReqVO) {
        return complainInfoMapper.getMyPublishList(pageReqVO);
    }


    private BusinessUserDO authBusinessUser() {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        BusinessUserDO businessUserDO = businessUserMapper.selectOne(new LambdaQueryWrapper<BusinessUserDO>().eq(BusinessUserDO::getUserId, loginUserId));
        if (businessUserDO == null) {
            throw exception(USER_NOT_EXISTS);
        }
        if (!BusinessUserEnum.AUDITED_STATUS.getCode().equals(businessUserDO.getStatus())) {
            throw exception(BUSINESS_STATUS_AUDIT);
        }
//        if (!BusinessUserEnum.AUTHENTICATED_AUTH.getCode().equals(businessUserDO.getIsAuth())) {
//            throw exception(BUSINESS_STATUS_AUTH);
//        }
        return businessUserDO;
    }

}
